<script setup lang="ts">
import { useDebounceFn } from '@vueuse/core'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import BigButton from '@/components/common/BigButton.vue'
import message from '@/components/common/message'
import PageController from '@/components/common/pagetable/PageController.vue'
import Select from '@/components/common/Select.vue'
import TextInput from '@/components/common/TextInput.vue'
import { Delete, Edit, Eye, Search, Student } from '@/components/icons'
import { deleteClass, getClassList, toggleClassVisibility } from '@/request/class'
import { useTeacherStore } from '@/store/teacher'

const router = useRouter()

// 搜索和筛选参数
const searchKeywords = ref('')
const gradeType = ref('')

// 班级数据
const classData = ref<{
  cid: string
  name: string
  school: string
  studentsNum: number
  gradeInt: number
  active: boolean
  invitationCode: string
}[]>([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(6)
const total = ref(0)

// 获取教师信息
const teacherStore = useTeacherStore()

// 获取班级列表
async function fetchClassList() {
  try {
    const data = await getClassList({
      school: teacherStore.teacher.school,
    })

    // 展开所有年级的班级
    let allClasses = data.entries.flatMap(entry =>
      entry.classes.map(cls => ({
        ...cls,
        gradeInt: entry.gradeInt,
      })),
    )

    // 根据筛选条件过滤数据（这里模拟后端筛选逻辑）
    if (gradeType.value) {
      allClasses = allClasses.filter(cls => cls.gradeInt === Number(gradeType.value))
    }

    if (searchKeywords.value) {
      allClasses = allClasses.filter(cls =>
        cls.name.includes(searchKeywords.value)
        || cls.school.includes(searchKeywords.value),
      )
    }

    classData.value = allClasses
    total.value = allClasses.length

    // 重新计算分页数据
    const totalPages = Math.ceil(total.value / pageSize.value)
    if (currentPage.value > totalPages && totalPages > 0) {
      currentPage.value = totalPages
    }
  }
  catch (error) {
    console.error('获取班级列表失败:', error)
    message.error('获取班级列表失败')
  }
}

// 分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return classData.value.slice(start, end)
})

// 删除班级
async function handleDeleteClass(cid: string) {
  // if (!confirm(`确定要删除班级"${className}"吗？此操作不可恢复！`)) {
  //   return
  // }

  try {
    await deleteClass({ cid })
    message.success('班级删除成功')
    fetchClassList() // 重新获取数据
  }
  catch (error) {
    console.error('删除班级失败:', error)
    message.error('删除班级失败')
  }
}

// 切换班级显示状态
async function handleToggleVisibility(cid: string, isActive: boolean) {
  const action = isActive ? '隐藏' : '显示'

  try {
    await toggleClassVisibility({ cid })
    message.success(`班级${action}成功`)
    fetchClassList() // 重新获取数据
  }
  catch (error) {
    console.error(`${action}班级失败:`, error)
    message.error(`${action}班级失败`)
  }
}

// 编辑班级
function handleEditClass(cid: string) {
  router.push(`/class/create-class/${cid}`)
}

// 创建班级
function handleCreateClass() {
  router.push('/class/create-class')
}

// 防抖处理搜索
const handleSearchUpdate = useDebounceFn(() => {
  currentPage.value = 1 // 搜索时重置到第一页
  fetchClassList() // 重新请求数据
}, 600)

// 年级筛选变化
function handleGradeChange() {
  currentPage.value = 1 // 筛选时重置到第一页
  fetchClassList() // 重新请求数据
}

// 页码变化
function handlePageChange(page: number) {
  currentPage.value = page
}

// 获取班级列表
teacherStore.addCallback(fetchClassList)
</script>

<template>
  <div class="content-header">
    班级管理
  </div>
  <div class="card-area filter-options">
    <Select
      v-model:model-value="gradeType"
      label="年级:"
      placeholder="全部年级"
      :options="[
        { label: '全部年级', value: '' },
        { label: '一年级', value: '1' },
        { label: '二年级', value: '2' },
        { label: '三年级', value: '3' },
        { label: '四年级', value: '4' },
        { label: '五年级', value: '5' },
        { label: '六年级', value: '6' },
      ]"
      @update:model-value="handleGradeChange"
    />
    <TextInput
      v-model="searchKeywords"
      label="搜索:"
      placeholder="搜索关键词"
      @update:model-value="handleSearchUpdate"
    >
      <template #suffix>
        <Search />
      </template>
    </TextInput>
  </div>
  <div class="filter-result">
    <div class="class-group">
      <div v-for="classItem in paginatedData" :key="classItem.cid" class="class-card card-area">
        <div class="header-info">
          <img src="/classroom.png" alt="">
          <div class="mask" :class="{ inactive: !classItem.active }">
            <div class="school-info">
              {{ classItem.school }}
            </div>
            <div class="class-info">
              {{ classItem.name }}
            </div>
            <div v-if="!classItem.active" class="inactive-label">
              已隐藏
            </div>
          </div>
        </div>
        <div class="info">
          <div class="student">
            <Student />
            <span class="student-number">{{ classItem.studentsNum }}</span>
            <span>名学生</span>
          </div>
          <div class="actions">
            <Edit @click="handleEditClass(classItem.cid)" />
            <Delete class="delete-class-btn" @click="handleDeleteClass(classItem.cid)" />
            <Eye
              :close="classItem.active"
              class="visibility-toggle"
              @click="handleToggleVisibility(classItem.cid, classItem.active)"
            />
          </div>
        </div>
      </div>
    </div>
    <PageController
      :page="currentPage"
      :total="total"
      :page-size="pageSize"
      @update:page="handlePageChange"
    />
  </div>
  <BigButton text="新增班级" @click="handleCreateClass" />
</template>

<style scoped>
.delete-class-btn {
  &:hover {
    stroke: rgb(255, 92, 92);
  }
  stroke: #949494;
}

.card-area.filter-options {
  padding: 18px 12px;
  margin-top: 12px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 25px;
}

.filter-result {
  margin-top: 24px;
  margin-bottom: 44px;

  .class-group {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 24px;

    .class-card {
      overflow: hidden;

      .header-info {
        position: relative;

        img {
          width: 100%;
        }

        .mask {
          position: absolute;
          width: 100%;
          height: 100%;
          bottom: 0;
          background: linear-gradient(
            to right,
            rgba(40, 74, 249, 0.75) 0%,
            rgba(81, 110, 252, 0.8) 46.15%,
            rgba(122, 145, 254, 0.6) 92.31%
          );
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;

          &.inactive {
            background: linear-gradient(
              to right,
              rgba(180, 180, 180, 0.75) 0%,
              rgba(160, 160, 160, 0.8) 46.15%,
              rgba(140, 140, 140, 0.6) 92.31%
            );
          }

          .school-info {
            font-size: 10px;
            color: #ffffff;
          }

          .class-info {
            font-size: 20px;
            color: #ffffff;
            text-shadow: 0px 0px 4px rgba(0, 0, 0, 0.25);
          }

          .inactive-label {
            font-size: 12px;
            color: #ffffff;
            background: rgba(255, 255, 255, 0.2);
            padding: 2px 8px;
            border-radius: 4px;
            margin-top: 4px;
          }
        }
      }

      .info {
        display: flex;
        background-color: white;
        justify-content: space-between;
        padding: 15px;

        .student {
          display: flex;
          align-items: center;

          .student-number {
            margin-left: 3px;
            letter-spacing: -0.06em;
            font-weight: 700;
            font-size: 15px;
            background: linear-gradient(360deg, #2447f9 41.62%, #7a91fe 71.67%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
          }
        }

        .actions {
          display: flex;
          align-items: center;
          gap: 12px;

          svg {
            cursor: pointer;
          }

          .visibility-toggle {
            stroke: currentColor;
            color: #949494;

            &:hover {
              color: var(--primary-color);
            }
          }
        }
      }
    }
  }
}
</style>
